package com.todo.admin.service.login;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSONObject;
import com.todo.admin.common.base.async.AsyncTaskFactory;
import com.todo.admin.common.cache.GuavaCacheService;
import com.todo.admin.common.cache.MapCache;
import com.todo.admin.common.cache.RedisCacheService;
import com.todo.admin.common.thread.ThreadPoolManager;
import com.todo.admin.entity.enums.common.ConfigKeyEnum;
import com.todo.admin.entity.enums.common.LoginStatusEnum;
import com.todo.admin.service.login.dto.ConfigDTO;
import com.todo.admin.system.user.db.SysUserEntity;
import com.todo.common.utils.ServletHolderUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class LoginService {

    private final RedisCacheService redisCache;

    private final GuavaCacheService guavaCache;

    /**
     * 获取验证码 data
     *
     * @return {@link ConfigDTO}
     */
    public ConfigDTO getConfig() {
        ConfigDTO configDTO = new ConfigDTO();

        boolean isCaptchaOn = isCaptchaOn();
        configDTO.setIsCaptchaOn(isCaptchaOn);
        configDTO.setDictionary(MapCache.dictionaryCache());
        return configDTO;
    }


    /**
     * 记录登录信息
     */
    public void recordLoginInfo(String username, Long userId) {
        ThreadPoolManager.execute(AsyncTaskFactory.loginInfoTask(username, LoginStatusEnum.LOGIN_SUCCESS,
                LoginStatusEnum.LOGIN_SUCCESS.description()));

        SysUserEntity entity = JSONObject.parseObject(redisCache.userCache.getObjectById(userId), SysUserEntity.class);

        entity.setLoginIp(ServletUtil.getClientIP(ServletHolderUtil.getRequest()));
        entity.setLoginDate(DateUtil.date());
        entity.updateById();
    }


    private boolean isCaptchaOn() {
        return Convert.toBool(guavaCache.configCache.get(ConfigKeyEnum.CAPTCHA.getValue()));
    }

}
